package at.tuwien.seminar.scrum1.view.wicket.reservation;

import at.tuwien.seminar.scrum1.model.Bill;
import at.tuwien.seminar.scrum1.model.Reservation;
import at.tuwien.seminar.scrum1.proxies.BillProxy;
import at.tuwien.seminar.scrum1.proxies.ReservationProxy;
import at.tuwien.seminar.scrum1.utils.DateUtils;
import at.tuwien.seminar.scrum1.view.error.ProblemPage;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

import java.util.Date;

public class ReservationCloseActionPanel extends Panel
{
    /**
     * @param id
     *            component id
     * @param model
     *            model for contact
     */
    public ReservationCloseActionPanel(String id, final IModel<Reservation> model)
    {
        super(id, model);
        add(new Link("select")
        {
            @Override
            public void onClick()
            {
            	Reservation reservation = model.getObject();

                Date date = new Date();

                if (!reservation.isClosed()) {
                    if(reservation.getStartDate().getTime() < date.getTime())
                    {
                        double price;

                        Bill bill = new Bill();

                        if (reservation.getEndDate().getTime() < date.getTime()) {
                            price = reservation.getPrice();
                        } else {
                            Long shouldMonth = DateUtils.daysBetween(reservation.getStartDate(), reservation.getEndDate());
                            Long actualMonth = DateUtils.daysBetween(reservation.getStartDate(), date);

                            double percentage =  (actualMonth.doubleValue()/shouldMonth.doubleValue());

                            price = reservation.getPrice() * percentage;
                        }


                        bill.setPrice(price);
                        bill.setCustomers(reservation.getCustomers());
                        bill.setBillDate(date);

                        BillProxy.getInstance().insertBill(bill);

                        reservation.setClosed(true);

                        ReservationProxy.getInstance().updateReservation(reservation);

                    }
                    else
                        setResponsePage(new ProblemPage(reservation));
                } else {
                     setResponsePage(new ProblemPage(reservation));
                }
            }
        });
    }
}
